package myky.com.doctorapp.utils;

/**
 * Created by 61904 on 2017/7/25.
 */

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.ContextCompat;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;


import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import myky.com.doctorapp.api.Address;

/**
 * 系统工具类
 * Created by zhuwentao on 2016-07-18.
 */
public class SystemUtil {

    private static Pattern p = Pattern.compile("^((13[0-9])|(15[^4])|(18[0-9])|(17[0-8])|(147,145))\\d{8}$");

    /**
     * 获取屏幕分辨率
     *
     * @return
     */
    public static int[] getMetrics(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        Point point = new Point();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            display.getSize(point);
        }
        int width = point.x;
        int height = point.y;
        int[] metrics = {width, height};

        return metrics;
    }

    /**
     * 获取当前手机系统语言。
     *
     * @return 返回当前系统语言。例如：当前设置的是“中文-中国”，则返回“zh-CN”
     */
    public static String getSystemLanguage() {
        return Locale.getDefault().getLanguage();
    }

    /**
     * 获取当前系统上的语言列表(Locale列表)
     *
     * @return 语言列表
     */
    public static Locale[] getSystemLanguageList() {
        return Locale.getAvailableLocales();
    }

    /**
     * 获取当前手机系统版本号
     *
     * @return 系统版本号
     */
    public static String getSystemVersion() {
        return Build.VERSION.RELEASE;
    }

    /**
     * 获取手机型号
     *
     * @return 手机型号
     */
    public static String getSystemModel() {
        return Build.MODEL;
    }

    /**
     * 获取手机厂商
     *
     * @return 手机厂商
     */
    public static String getDeviceBrand() {
        return Build.BRAND;
    }

    /**
     * 获取手机IMEI(需要“android.permission.READ_PHONE_STATE”权限)
     *
     * @return 手机IMEI
     */
    @SuppressLint("MissingPermission")
    public static String getIMEI(Context ctx) {
        TelephonyManager tm = (TelephonyManager) ctx.getSystemService(Activity.TELEPHONY_SERVICE);
        if (tm != null) {
            return tm.getDeviceId();
        }
        return "获取唯一标识失败";
    }

    /**
     * 意见反馈上传的版本信息
     */


    public static void mPhoneInfo() {

        String phoneInfo = "Product: " + Build.PRODUCT;
        phoneInfo += "\n CPU_ABI: " + Build.CPU_ABI;
        phoneInfo += "\n TAGS: " + Build.TAGS;
        phoneInfo += "\n VERSION_CODES.BASE: " + Build.VERSION_CODES.BASE;
        phoneInfo += "\n MODEL: " + Build.MODEL;
        phoneInfo += "\n SDK: " + Build.VERSION.SDK;
        phoneInfo += "\n VERSION.RELEASE: " + Build.VERSION.RELEASE;
        phoneInfo += "\n DEVICE: " + Build.DEVICE;
        phoneInfo += "\n DISPLAY: " + Build.DISPLAY;
        phoneInfo += "\n BRAND: " + Build.BRAND;
        phoneInfo += "\n BOARD: " + Build.BOARD;
        phoneInfo += "\n FINGERPRINT: " + Build.FINGERPRINT;
        phoneInfo += "\n ID: " + Build.ID;
        phoneInfo += "\n MANUFACTURER: " + Build.MANUFACTURER;
        phoneInfo += "\n CODENAME: " + Build.VERSION.CODENAME;
        phoneInfo += "\n INCREMENTAL: " + Build.VERSION.INCREMENTAL;
        phoneInfo += "\n BOOTLOADER: " + Build.BOOTLOADER;
        phoneInfo += "\n SERIAL: " + Build.SERIAL;
        phoneInfo += "\n UNKNOWN: " + Build.UNKNOWN;


        Log.i("out", "phpne" + phoneInfo);


    }

    /**
     * 检查是否存在SDCard
     *
     * @return
     */
    public static boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 2 * 获取版本号 3 * @return 当前应用的版本号 4
     */
    public static int getVersion(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(),
                    0);
            String version = info.versionName;
            int versioncode = info.versionCode;
            return versioncode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }


    /**
     * 2 * 获取版本号 3 * @return 当前应用的版本名字 4
     */
    public static String getVersionName(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(),
                    0);
            String version = info.versionName;
            int versioncode = info.versionCode;
            return "v" + version;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "1.0.0";
    }

    /**
     * 获取系统时间
     *
     * @return
     */

    public static String getCurrentTime() {

        String date = null;
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
        Date curDate = new Date(System.currentTimeMillis());
        date = format.format(curDate);
        return date;
    }

    /**
     * 获取系统时间
     *
     * @return
     */

    public static String getCurrentTimeyyyy() {

        String date = null;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date curDate = new Date(System.currentTimeMillis());
        date = format.format(curDate);
        return date;
    }

    /**
     * 获取系统时间
     *
     * @return
     */

    public static String getCurrentTime_mm() {

        String date = null;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());
        date = format.format(curDate);
        return date;
    }

    /**
     * 比较两个日期的大小，日期格式为yyyy年MM月dd日
     *
     * @param str1 the first date
     * @param str2 the second date
     * @return true <br/>false
     */
    public static boolean isDateOneBigger(String str1, String str2) {
        boolean isBigger = false;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        Date dt1 = null;
        Date dt2 = null;
        try {
            dt1 = sdf.parse(str1);
            dt2 = sdf.parse(str2);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (dt1.getTime() > dt2.getTime()) {
            isBigger = true;
        } else if (dt1.getTime() < dt2.getTime()) {
            isBigger = false;
        }
        return isBigger;
    }

    /**
     * 比较两个日期的大小，日期格式为yyyy-MM-dd
     *
     * @param str1 the first date
     * @param str2 the second date
     * @return true <br/>false
     */
    public static boolean isDateOneBiggeryyyy(String str1, String str2) {
        boolean isBigger = false;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date dt1 = null;
        Date dt2 = null;
        try {
            dt1 = sdf.parse(str1);
            dt2 = sdf.parse(str2);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (dt1.getTime() > dt2.getTime()) {
            isBigger = true;
        } else if (dt1.getTime() < dt2.getTime()) {
            isBigger = false;
        }
        return isBigger;
    }


    /**
     * 比较病历授权两个日期的大小，日期格式为yyyy-MM-dd
     *
     * @param str1 the first date
     * @return true <br/>false
     */
    public static boolean isDatAuthor(String str1) {
        boolean isBigger = false;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date dt1 = null;
        Date dt2 = null;
        try {
            dt1 = sdf.parse(str1);
            dt2 = sdf.parse(getCurrentTimeyyyy());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (dt2.getTime() > dt1.getTime()) {
            isBigger = true;
        } else {
            isBigger = false;
        }
        return isBigger;
    }

    /**
     * year年Month月day日 改year-month-day
     *
     * @return
     */

    public static String getDefaultDate(String dates) {

        String date = null;
        try {
            String[] years = dates.split("年");
            String lastYear = years[0];
            String[] months = years[1].split("月");
            String lastMonth = months[0];
            String[] days = months[1].split("日");
            String lastDay = days[0];
            date = lastYear + "-" + lastMonth + "-" + lastDay;
        } catch (Exception e) {

        }
        return date;
    }

    /**
     * year-month-day->year年Month月day日
     *
     * @return
     */

    public static String getTextDate(String dates) {
        String date = null;
        try {
            String[] string = dates.split(" ");
            String[] strings = string[0].split("-");
            String lastYear = strings[0];
            String lastMonth = strings[1];
            String lastDay = strings[2];
            date = lastYear + "年" + lastMonth + "月" + lastDay + "日";
        } catch (Exception e) {

        }

        return date;
    }

    //时间戳转字符串-->yyyy年MM月dd日
    public static String getStrTime(long timeStamp) {
        String timeString = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        timeString = sdf.format(new Date(timeStamp));//单位秒
        return timeString;
    }
    //时间戳转字符串---yyyy-MM-dd
    public static String getStrTime_M(long timeStamp) {
        String timeString = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        timeString = sdf.format(new Date(timeStamp));//单位秒
        return timeString;
    }
    //时间戳转字符串---yyyy-MM-dd
    public static String getStrTime_MT(long timeStamp) {
        String timeString = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
        timeString = sdf.format(new Date(timeStamp));//单位秒
        return timeString;
    }
    //时间戳转字符串---hh:mm
    public static String getStrTime_T(long timeStamp) {
        String timeString = null;
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        timeString = sdf.format(new Date(timeStamp));//单位秒
        return timeString;
    }
    //时间戳转字符串---上下午
    public static String getStrTime_W(long timeStamp) {
        String timeString = null;
        SimpleDateFormat sdf = new SimpleDateFormat("HH");
        timeString = sdf.format(new Date(timeStamp));//单位秒

        if (Integer.parseInt(timeString)>12){
            timeString="下午";
        }else if (Integer.parseInt(timeString)==12){
            timeString="中午";
        }else {
            timeString="上午";
        }

        return timeString;
    }
    public static String betweenDays(long l) {

        String str = null;
        long currentTime = System.currentTimeMillis();
        long betweenDays = (long) ((l - (1000 * 60 * 60 * 24 * 14)));
        if (currentTime < betweenDays) {
            str = getStrTime(betweenDays);
        }
        return str;
    }

    /**
     * year-month-day-HH-MM-SS-->year-month-day
     *
     * @return
     */

    public static String getText_Date(String dates) {
        String date = null;
        try {
            String[] string = dates.split(" ");
            date = string[0];
        } catch (Exception e) {

        }

        Log.i("out", "date2." + date);
        return date;
    }

    /**
     * year-month->year年Month月
     *
     * @return
     */

    public static String getMonthDate(String dates) {
        String date = null;
        try {
            String[] string = dates.split("-");
            String lastYear = string[0];
            String lastMonth = string[1];
            date = lastYear + "年" + lastMonth + "月";
            Log.i("out", "date1." + date);
        } catch (Exception e) {

        }

        Log.i("out", "date2." + date);
        return date;
    }


    // 判断权限集合
    public static boolean lacksPermissions(Context context, String... permissions) {
        for (String permission : permissions) {
            if (lacksPermission(context, permission)) {
                return true;
            }
        }
        return false;
    }

    // 判断是否缺少权限
    private static boolean lacksPermission(Context context, String permission) {
        return ContextCompat.checkSelfPermission(context, permission) ==
                PackageManager.PERMISSION_DENIED;
    }



    //时间戳转化为时间
    public static String timesChanged(String timeStamp) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//这个是你要转成后的时间的格式
        String sd = sdf.format(new Date(Long.parseLong(String.valueOf(timeStamp))));   // 时间戳转换成时间
        return sd;
    }

    /**
     * 获取网络图片
     *
     * @param address 图片网络地址
     * @return Bitmap 返回位图
     */
    public static InputStream getInputStreamByUrl(String address) {
        URL url = null;
        HttpURLConnection urlConnection = null;
        try {
            url = new URL(address);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setConnectTimeout(2 * 1000);
            urlConnection.setRequestMethod("GET");
            return urlConnection.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    //获取系统当前时间的时间戳
    public static String getTime() {
        long timeStampSec = System.currentTimeMillis() / 1000;
        String timestamp = String.format("%010d", timeStampSec);
        return timestamp;
    }

    //获取时间差
    public static String formationDate(String date_create) {
        String dateString = date_create;
        // 获取系统当前时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date now = new Date();
        try {
            Date date = sdf.parse(date_create);
            long endTime = now.getTime();
            long currentTime = date.getTime();
            // 计算两个时间点相差的秒数
            long seconds = (endTime - currentTime);
            if (seconds < 10 * 1000) {
                dateString = "刚刚";
            } else if (seconds < 60 * 1000) {
                dateString = seconds / 1000 + "秒前";
            } else if (seconds < 60 * 60 * 1000) {
                dateString = seconds / 1000 / 60 + "分钟前";
            } else if (seconds < 60 * 60 * 24 * 1000) {
                dateString = seconds / 1000 / 60 / 60 + "小时前";
            } else if (seconds < 60 * 60 * 24 * 1000 * 30L) {
                dateString = seconds / 1000 / 60 / 60 / 24 + "天前";
            } else if (date.getYear() == now.getYear()) {//今年并且大于30天显示具体月日
                dateString = new SimpleDateFormat("MM-dd").format(date.getTime());
            } else if (date.getYear() != now.getYear()) {//大于今年显示年月日
                dateString = new SimpleDateFormat("yyyy-MM-dd").format(date.getTime());
            } else {
                dateString = new SimpleDateFormat("yyyy-MM-dd").format(date);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dateString;
    }


    /**
     * 根据
     * 1. "汉字区间"
     * 2. "数字区间"
     * 3. "小写字母区间"
     * 4. "大写字母区间"
     * 过滤掉非法字符的方法
     *
     * @param oldString
     * @return
     */
    public static String filterCharToNormal(String oldString) {
        StringBuilder stringBuilder = new StringBuilder();
        try {


            int length = oldString.length();
            for (int i = 0; i < length; i++) {//遍历传入的String的所有字符
                char codePoint = oldString.charAt(i);
//            if (//如果当前字符为常规字符,则将该字符拼入StringBuilder
//                    ((codePoint >= 0x4e00) && (codePoint <= 0x9fa5)) ||//表示汉字区间
//                            ((codePoint >= 0x30) && (codePoint <= 0x39)) ||//表示数字区间
//                            ((codePoint >= 0x41) && (codePoint <= 0x5a)) ||//表示大写字母区间
//                            ((codePoint >= 0x61) && (codePoint <= 0x7a))) {//小写字母区间
//                stringBuilder.append(codePoint);
//            } else {//如果当前字符为非常规字符,则忽略掉该字符
//            }
                if (!getIsEmoji(codePoint)) {
                    stringBuilder.append(codePoint);
                }
            }
        } catch (Exception e) {
        }
        return stringBuilder.toString();
    }

    public static boolean getIsEmoji(char codePoint) {
        if ((codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA)
                || (codePoint == 0xD)
                || ((codePoint >= 0x20) && (codePoint <= 0xD7FF))
                || ((codePoint >= 0xE000) && (codePoint <= 0xFFFD))
                || ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF)))
            return false;
        return true;
    }


    //判断数据流量是否可用 true:数据流量 false:非数据流量
    public static boolean isMobileConnected(Context context) {
        boolean isMobile = false;
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (activeNetworkInfo != null) {
                if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                    isMobile = true;
                } else {
                    isMobile = false;
                }
            }
        }
        return isMobile;
    }

    /**
     * 验证手机号码格式
     *
     * @param mobiles
     * @return
     */
    public static boolean isMobilePhone(String mobiles) {
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    /**
     * 检测当的网络（WLAN、3G/2G）状态
     * @param context Context
     * @return true 表示网络可用
     */
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (info != null && info.isConnected()) {
                //这里可以得到网络状态网络类型等网络相关信息
                // 当前网络是连接的
                if (info.getState() == NetworkInfo.State.CONNECTED) {
                    // 当前所连接的网络可用
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 通过URl获取里面的MD5
     * @param s
     * @return
     */
    public static String getPath_Md5(String s) {
        String md5 = null;
        String url = Address.IMAGE;
        if (!TextUtils.isEmpty(s)) {
            String[] split = s.split(url);
            md5 = split[1];
        }
        return md5;
    }
}
